package org.javacraft.qa.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author jan
 */
public class XMLUtils {

  private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss" );

  public static String getElementString( final String xml, final String elementName ) {
    final Pattern pattern = Pattern.compile( ".*\\<" + elementName + "\\>(.*)\\</" + elementName + "\\>.*", Pattern.MULTILINE | Pattern.DOTALL );
    final Matcher matcher = pattern.matcher( xml );
    if ( matcher.find() ) {
      return matcher.group( 1 );
    } else {
      return null;
    }
  }

  public static Date getElementDate( final String xml, final String elementName ) {
    try {
      final String value = getElementString( xml, elementName );
      return value == null ? null : DATE_FORMAT.parse( value );
    } catch ( ParseException ex ) {
      throw new RuntimeException( ex );
    }
  }

  public static Integer getElementInteger( final String xml, final String elementName ) {
    try {
      final String value = getElementString( xml, elementName );
      return value == null ? null : Integer.parseInt( value );
    } catch ( Exception ex ) {
      throw new RuntimeException( ex );
    }
  }
}
